<?php

namespace api\modules\app\controllers;

use api\components\DataCenter;
use api\components\GeoService;
use api\models\UploadForm;
use api\modules\app\models\EventFilterOuter;
use api\modules\app\services\CountService;
use api\modules\app\services\EventFileService;
use api\modules\app\services\UnitService;
use api\services\WechatService;
use api\traits\ControllerTrait;
use api\traits\LoginTrait;
use Swagger\Annotations\Get;
use Yii;
use yii\helpers\ArrayHelper;
use yii\rest\Controller;
use yii\web\UploadedFile;

class SiteController extends Controller
{
    use LoginTrait;
    use ControllerTrait;

    public function actionLogin()
    {
        $params = $this->getParams();
        $encrypt = isset($params['encrypt']) ? $params['encrypt'] : '';
        if ($encrypt) {
            $password = base64_decode(substr($params['password'],3));
        } else {
            $password = $params['password'];
        }
        $data = $this->loginByUsername($params['username'], $password);
//        $data = $this->loginByUsernameNew($params['username'], $params['password']);

        return $this->makeApiData(['data' => $data],[]);
    }

    public function actionLoginByToken()
    {
        $headers = \Yii::$app->request->headers;
        $data = $this->loginByToken($headers['authorization'], true);
        return $this->makeApiData(['data' => $data],[]);
    }

    public function actionLogout()
    {
        $headers = \Yii::$app->request->headers;
        $data = $this->logout($headers['authorization']);
        return $this->makeApiData(['data' => $data],[]);
    }

    public function actionForm()
    {
        $formId = $this->getQuery('form_id');
        $response = \Yii::$app->flowCenter->getForm($formId);

        return [
            'code' => 0,
            'data' => [
                'form' => [
                    'id' => $response['form_construction']['id'],
                    'formConstruction' => $response['form_construction']['form_construction'],
                ],
                'data' => [],
            ],
        ];
    }

    public function actionFormSubmit()
    {
        return [
            'code' => 0,
            'data' => $this->getParams(),
            'message' => '成功'
        ];
    }

    public function actionUpload()
    {
        $opter = $this->getUser();
        // 不需要落本地，基本不需要该 model，留着做 validate 比较方便
        $upload = new UploadForm();
        $upload->imgs = UploadedFile::getInstancesByName('imgs');
        $upload->audios = UploadedFile::getInstancesByName('audios');
        $upload->videos = UploadedFile::getInstancesByName('videos');
        $upload->docs = UploadedFile::getInstancesByName('docs');
        $upload->file = UploadedFile::getInstancesByName('file');
        $upload->files = UploadedFile::getInstancesByName('files');

        // 直接使用 UploadedFile（temp 文件）上传到问价服务器
        $result['imgs'] = $this->uploadFiles($upload->imgs, $opter);
        $result['audios'] = $this->uploadFiles($upload->audios, $opter);
        $result['videos'] = $this->uploadFiles($upload->videos, $opter);
        $result['docs'] = $this->uploadFiles($upload->docs, $opter);
        $result['file'] = $this->uploadFiles($upload->file, $opter);
        $result['files'] = $this->uploadFiles($upload->files, $opter);
        // if (!$upload->upload()) {
        //     // 是否有必要落一份在本地
        //     throw new Exception('Save files faild');
        // }
        $data = [];
        foreach ($result as $key => $value) {
            if (empty($value)) {
                $data[$key] = [];
                continue;
            }
            $data[$key] = ArrayHelper::getColumn($value, 'path');
        }

        return [
            'code' => 0,
            'data' => $data,
            'message' => '成功'
        ];
    }

    public function uploadFiles($files, $opter)
    {
        $originFiles = [];
        if (!is_array($files)) {
            $originFiles[] = $files;
        } else {
            $originFiles = $files;
        }
        foreach ($originFiles as $key => $file) {
            try {
                $path = Yii::$app->fileServer->uploadFile($file, ['user_id' => $opter['id']]);
                $filePath[] = $path;
            } catch (\Exception $e) {
                throw new \Exception('文件上传失败' . $e->getMessage());
            }
        }

        return $filePath;
    }

    /**
     * 政务微信根据 code 登录
     */
    public function actionLoginByCode()
    {
        \Yii::error('===loginbycode======start');
        $app = Yii::$app->request->headers->get('app');
        if (empty($app)) {
            $app = $this->getQuery('app', '');
        }
        $env = $this->getQuery('env');
        $channel = $this->getQuery('channel', 'ls');
        $category = $this->getQuery('category', 'zw');
        $code = $this->getQuery('code');
        $data = (new WechatService($env, $app, $channel))->loginByWechatCode($code, $category);
        \Yii::error('===loginbycode======'.json_encode($data));
        return [
            'code' => 200,
            'data' => $data['data'],
            'message' => '成功'
        ];
    }

    public function actionTest() {
        $params = Yii::$app->request->getQueryParams();
        $res = UnitService::fillCood($params);
        print_r($res);exit;
    }

//    public function actionLoginByToken()
//    {
//        $token = $this->getToken();
//        $data = $this->loginByToken($token, true);
////        CountService::reloadCache($data, $data['token']);
//        return $this->makeApiData(['data' => $data],[]);
//    }
}

